package cn.dlc.com.config.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class LoginFilter implements GlobalFilter, Ordered {

    /**
     * 这个Mono就是一个非阻塞的请求了，Spring WebFlux
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("customer filter...");

        // 获取请求参数里面的token
        String token = exchange.getRequest().getQueryParams().getFirst("access-token");

        System.out.println("ip: " + exchange.getRequest().getHeaders().getFirst("Host"));
        // 判断是否存在属性
        if(StringUtils.isBlank(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 继续执行，
        return chain.filter(exchange);
    }

    /**
     * 执行顺序，值越小，执行优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
